package org.csu.wuliu.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.csu.wuliu.domain.*;
import org.csu.wuliu.persistence.ItemMapper;
import org.csu.wuliu.persistence.LineItemMapper;
import org.csu.wuliu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@ResponseBody
public class TaskController {
    @Autowired
    private TaskService taskService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private LineItemMapper lineItemMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private SubmanageController submanageController;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private SubstationService substationService;


    @PostMapping("/task/searchBySubstationAndStatus")
    public JSONArray search(@RequestBody String jsonString) {
        JSONObject json = JSONObject.parseObject(jsonString);
        JSONArray jsonArray = new JSONArray();
        List<Task> taskList = taskService.getTaskListBySubstationAndStatus(json.getString("substationId"), json.getInteger("status"));
        JSONObject jsonResult = new JSONObject();
        if (taskList == null) {
            String msg = "该任务单不存在";
            json.put("message", msg);
            jsonArray.add(jsonResult);
            return jsonArray;
        } else {
            for (Task task : taskList) {
                json.put("taskId", task.getTaskId());
                Order order = orderService.getOrder(task.getOrderId());
                json.put("orderId", order.getOrderId());
                json.put("distributorId", task.getDistributorId());
                json.put("status", task.getStatus());
                String username = order.getUsername();
                User user = userService.getUserByusername(username);
                json.put("username", username);
                json.put("orderDate", order.getOrderDate());
                json.put("status", order.getStatus());
                json.put("address", user.getAddress());
                json.put("tel", user.getTel());
                List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
                System.out.println(lineItems);
                BigDecimal count = new BigDecimal("0");
                for (LineItem lineItem : lineItems) {
                    json.put("lineItem", lineItem);
                    String itemId = lineItem.getItemId();
                    Item item = itemMapper.getItem(itemId);
                    json.put("productId", item.getProductId());
                    json.put("categoryId", item.getCategoryId());
                    count = count.add(lineItem.calculateTotal());
                }
                json.put("totalprice", count);
                jsonArray.add(json);
            }
            return jsonArray;
        }
    }


    /*
    {
    "address": "重庆",
    "lineItem": {
        "orderId": "OD202007110001",
        "itemId": "3",
        "number": 4,
        "listprice": 100.0
    },
    "productId": "1",
    "orderId": "OD202007110001",
    "distributorId": "1088",
    "totalprice": 1000.0,
    "tel": "15736076132",
    "orderDate": "2020-07-10T16:00:00.000+00:00",
    "taskId": "TS202007110001",
    "status": 1,
    "username": "wunanxi"
}
     */
    @GetMapping("/task/searchByTaskId")
    public JSONObject searchByTaskId(@RequestParam String taskId) {
        Task task = taskService.getTaskByTaskId(taskId);
        JSONObject json = new JSONObject();
        if (task == null) {
            String msg = "该任务单不存在";
            json.put("message", msg);
            return json;
        } else {
            json.put("taskId", task.getTaskId());
            Order order = orderService.getOrder(task.getOrderId());
            json.put("orderId", order.getOrderId());
            json.put("distributorId", task.getDistributorId());
            json.put("status", task.getStatus());
            User user = userService.getUserByusername(order.getUsername());
            json.put("username", order.getUsername());
            json.put("orderDate", order.getOrderDate());
            json.put("status", order.getStatus());
            json.put("address", user.getAddress());
            json.put("tel", user.getTel());
            List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
            System.out.println(lineItems);
            BigDecimal count = new BigDecimal("0");
            for (LineItem lineItem : lineItems) {
                json.put("lineItem", lineItem);
                String itemId = lineItem.getItemId();
                Item item = itemMapper.getItem(itemId);
                json.put("productId", item.getProductId());
                json.put("categoryId", item.getCategoryId());
//                json.put("desc", item.getDescn());
                count = count.add(lineItem.calculateTotal());
            }
            json.put("totalprice", count);
            return json;
        }
    }


    @GetMapping("/task/searchByOrderId")
    public JSONObject searchByOrderId(@RequestParam String orderId) {
        Task task = taskService.getTaskByOrderId(orderId);
        JSONObject json = new JSONObject();
        if (task == null) {
            String msg = "该任务单不存在";
            json.put("message", msg);
            return json;
        } else {
            json.put("taskId", task.getTaskId());
            Order order = orderService.getOrder(task.getOrderId());
            json.put("orderId", order.getOrderId());
            json.put("distributorId", task.getDistributorId());
            json.put("status", task.getStatus());
            User user = userService.getUserByusername(order.getUsername());
            json.put("username", order.getUsername());
            json.put("orderDate", order.getOrderDate());
            json.put("status", order.getStatus());
            json.put("address", user.getAddress());
            json.put("tel", user.getTel());
            List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
            System.out.println(lineItems);
            BigDecimal count = new BigDecimal("0");
            for (LineItem lineItem : lineItems) {
                json.put("lineItem", lineItem);
                String itemId = lineItem.getItemId();
                Item item = itemMapper.getItem(itemId);
                json.put("productId", item.getProductId());
                json.put("categoryId", item.getCategoryId());
                count = count.add(lineItem.calculateTotal());
            }
            json.put("totalprice", count);
            return json;
        }
    }

    @GetMapping("/task/searchByDistributor")
    public JSONArray getTaskListByDistributorId(@RequestParam String distributorId) {
        List<Task> taskList = taskService.getTaskListByDistributorId(distributorId);
        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (taskList == null) {
            String msg = "该任务列表不存在";
            json.put("message", msg);
            jsonArray.add(json);
            return jsonArray;
        } else {
            for (Task task : taskList) {
                json.put("taskId", task.getTaskId());
                Order order = orderService.getOrder(task.getOrderId());
                json.put("orderId", order.getOrderId());
                json.put("distributorId", task.getDistributorId());
                json.put("status", task.getStatus());
                User user = userService.getUserByusername(order.getUsername());
                json.put("username", order.getUsername());
                json.put("orderDate", order.getOrderDate());
                json.put("status", order.getStatus());
                json.put("address", user.getAddress());
                json.put("tel", user.getTel());
                List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
                System.out.println(lineItems);
                BigDecimal count = new BigDecimal("0");
                for (LineItem lineItem : lineItems) {
                    json.put("lineItem", lineItem);
                    String itemId = lineItem.getItemId();
                    Item item = itemMapper.getItem(itemId);
                    json.put("productId", item.getProductId());
                    json.put("categoryId", item.getCategoryId());
                    count = count.add(lineItem.calculateTotal());
                }
                json.put("totalprice", count);
                jsonArray.add(json);
            }
            return jsonArray;
        }
    }

    @GetMapping("/task/searchByUsername")
    public JSONArray searchByUsername(@RequestParam String username) {
        List<Task> taskList = taskService.getTaskListByUsername(username);
        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (taskList == null) {
            String msg = "该任务列表不存在";
            json.put("message", msg);
            jsonArray.add(json);
            return jsonArray;
        } else {
            for (Task task : taskList) {
                json.put("taskId", task.getTaskId());
                Order order = orderService.getOrder(task.getOrderId());
                json.put("orderId", order.getOrderId());
                json.put("distributorId", task.getDistributorId());
                json.put("status", task.getStatus());
                User user = userService.getUserByusername(username);
                json.put("username", username);
                json.put("orderDate", order.getOrderDate());
                json.put("status", order.getStatus());
                json.put("address", user.getAddress());
                json.put("tel", user.getTel());
                List<LineItem> lineItems = lineItemMapper.getLineItemsByOrderId(order.getOrderId());
                System.out.println(lineItems);
                BigDecimal count = new BigDecimal("0");
                for (LineItem lineItem : lineItems) {
                    json.put("lineItem", lineItem);
                    String itemId = lineItem.getItemId();
                    Item item = itemMapper.getItem(itemId);
                    json.put("productId", item.getProductId());
                    json.put("categoryId", item.getCategoryId());
                    count = count.add(lineItem.calculateTotal());
                }
                json.put("totalprice", count);
                jsonArray.add(json);
            }
            return jsonArray;
        }
    }


    //人工调度
    //{
    //   "taskId" : "TS202007110002",
    //   "orderId" : "OD202007110002",
    //   "distributorId":"5555",
    //   "status":"1",
    //   "substationId":"sh"
    //}

    @PostMapping("/task/dispatch")
    public ResponseEntity<String> dispatch(@RequestBody String jsonString) {
        JSONObject json = JSONObject.parseObject(jsonString);
        Task task = new Task();
        task.setTaskId(json.getString("taskId"));
        task.setDistributorId(json.getString("distributorId"));
        task.setOrderId(json.getString("orderId"));
        task.setStatus(json.getInteger("status"));
        task.setSubstationId(json.getString("substationId"));
        taskService.insertTask(task);
        //修改订单状态
        Order order = orderService.getOrder(json.getString("orderId"));
        order.setStatus(4);
        orderService.updateOrder(order);
        submanageController.handoutTask(json.getString("taskId"));
        return new ResponseEntity<String>("调度成功", HttpStatus.OK);
    }


    @PostMapping("/task/update")
    public ResponseEntity<String> taskUpdate(@RequestBody Task task) {
        taskService.updateTask(task);
//        subManageController.handoutTask();

        return new ResponseEntity<String>("调度成功", HttpStatus.OK);
    }


    @GetMapping("/task/auto")
    public Task autoMatch(@RequestParam String orderId) {
        Order order = orderService.getOrder(orderId);
        User user = userService.getUserByusername(order.getUsername());
        Task task = taskService.getTaskByOrderId(order.getOrderId());
        ArrayList<String> address = getAllAdresss();
        System.out.println(user.getAddress());
        //先根据地址进行分配
        for (String ad : address) {
            System.out.println(ad);
            if (ad.equals(user.getAddress())) {
                System.out.println("进入");
                Substation substation = substationService.getSubstaionByAddress(ad);
                task.setSubstationId(substation.getSubstationId());
                //task.setStatus(1);
                taskService.updateTask(task);
                submanageController.handoutTask(task.getTaskId());
                break;
            }
        }
        //若找不到 则根据各个分站的任务单数量进行分配
        if (task.getStatus() == 0) {
            List<String> list = taskService.getLeastTaskSub();
            task.setSubstationId(list.get(0));
            //task.setStatus(1);
            taskService.updateTask(task);
            submanageController.handoutTask(task.getTaskId());

        }
        order.setStatus(4);
        orderService.updateOrder(order);
        Task task1 = taskService.getTaskByOrderId(orderId);
        //返回任务单分配的结果
        return task1;

    }

    public ArrayList<String> getAllAdresss() {
        ArrayList<String> address = new ArrayList<>();
        List<Substation> substations = substationService.getSubstationList();
        for (Substation substation : substations) {
            address.add(substation.getAddress());
        }
        return address;

    }

    //新增内容
    @ResponseBody
    @GetMapping("/task/getorders")
    public List<Order> getordersByStatus() {
        System.out.println("来了");
        List<Order> orders = orderService.getOrdersByOrderStatus(2);
        return orders;
    }
}
